package com.lzk.filter;
import com.alibaba.fastjson.JSON;
import com.lzk.common.BaseUtils;
import com.lzk.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter(filterName = "loginCheckFilter",urlPatterns = "/*")
@Slf4j
public class loginCheckFilter implements Filter {

    private static final AntPathMatcher PATH_MATCHER=new AntPathMatcher();//比较路径用的
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        String[] needToChain ={
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**",
                "/common/**",
                "/user/sendMsg",
                "/user/login"
        };
        HttpServletRequest request=(HttpServletRequest)servletRequest;
        HttpServletResponse response=(HttpServletResponse)servletResponse;
        String requestURI = request.getRequestURI();
        if (check(needToChain,requestURI)){
            log.info("不需要处理的路径:{}",requestURI);
            filterChain.doFilter(request,response);//不用处理，直接放行
            return;
        }
        //需要处理
        HttpSession session = request.getSession();
        Long emp = (Long) session.getAttribute("emp");
        if (emp != null){//登录了
            BaseUtils.setEmpId(emp);
            filterChain.doFilter(request,response);
            return;
        }
        //判断移动端的登录状态
        Long userId = (Long) session.getAttribute("user");
        if (userId != null){
            BaseUtils.setEmpId(userId);
            filterChain.doFilter(request,response);
            return;
        }
        log.info("拦截到路径：{}",requestURI);
        log.info("用户未登录");
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));

    }

    public boolean check(String[]urls,String requestURI){
        for (String url : urls) {
            boolean flag = PATH_MATCHER.match(url, requestURI);//判断请求的路径是否需要处理
            if (flag){
                return true;//不需要处理
            }
        }
        return false;//需要处理
    }
}
